import 'dart:io';

import 'package:android_intent_plus/android_intent.dart';
import 'package:chathouse/public/Config.dart';
import 'package:chathouse/util/base_utils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';

import '../net/ApiPath.dart';

class AppUpdateWidget {
  static showUpdateDialog(String updateMsg, String version,
      {bool isForcedUpdate = false}) {
    Get.defaultDialog(
      barrierDismissible: false,
      onWillPop: () async {
        return false;
      },
      title: "發現新版本$version",
      content: Text(updateMsg),
      actions: [
        Visibility(
          visible: !isForcedUpdate,
          child: TextButton(
            child: Text("暫不更新",
                style: getTextStyle(18.sp, fontType: FontType.BOLD)),
            onPressed: () {
              Get.back();
            },
          ),
        ),
        TextButton(
          child:
              Text("立即更新", style: getTextStyle(18.sp, fontType: FontType.BOLD)),
          onPressed: () {
            if (Platform.isIOS) {
              _launchURL(ApiPath.IOSUrl);
            } else if (Platform.isAndroid) {
              const AndroidIntent intent = AndroidIntent(
                action: 'action_view',
                data:
                    'https://play.google.com/store/apps/details?id=com.hk.chathouse',
              );
              intent.launch().catchError((error) {
                ToastUtil.showToast("跳轉出錯:${error.toString()}");
              });
            }
            if (!isForcedUpdate) {
              Get.back();
            }
          },
        ),
      ],
    );
  }

  static _launchURL(_url) async => await canLaunch(_url)
      ? await launch(_url)
      : throw 'Could not launch $_url';
}
